//
//  RetryNetQueue.m
//  云成绩
//
//  Created by apple on 2017/8/21.
//  Copyright © 2017年 zj. All rights reserved.
//

#import "RetryNetQueue.h"
#import "Reachability.h"

@interface RetryNetQueue ()

@property (nonatomic, strong) RequestNormal *currentRequest;
@property (nonatomic, strong) NSMutableArray<__kindof RequestNormal *> *queue;
@property (nonatomic, copy) dispatch_block_t releaseBlock;

@end


@implementation RetryNetQueue

- (instancetype)initWithRelease:(dispatch_block_t)block {
    self = [super init];
    if (self) {
        //App.isNet = YES;
        self.releaseBlock = [block copy];
        self.queue = [NSMutableArray arrayWithCapacity:1];
        NSString *urlStr = @"www.baidu.com";
        Reachability *netConnect = [Reachability reachabilityWithHostName:urlStr];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
        
        [netConnect startNotifier];
    }
    return self;
}

// 通知监听的事件
-(void)reachabilityChanged:(NSNotification *)note{
    //设置了缓冲区，在1秒内多次触发这个函数 将会只执行最后一次，妈的，这里有时候一次要调用两下。
    //取消的函数 必须要和 传入的函数 带的值一样
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateInterfaceWithReachability) object:nil];
    
    [self performSelector:@selector(updateInterfaceWithReachability) withObject:nil afterDelay:1];
    
    
}
//网络连接该干活了
-(void)updateInterfaceWithReachability{
    
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    // 创建请求（requset）
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];//缓存策略：基础策略，超时设置：10秒
    // 连接服务器
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    
    
}
//出现错误
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    //App.isNet = NO;
    NSLog(@"连接出错，判定为没有网");

}
//接收到反馈信息
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"收到百度的回应，判定为有网");
    //App.isNet = YES;
//    [self afreshOrderToServer];
    [self start];
}

- (void)appendFailureNetRequest:(RequestNormal *)request onSuccess:(OnSuccess)successBlock{
    request.blockMap[@"onSuccess"] = [successBlock copy];
    [self.queue addObject:request];
    //if (App.isNet) [self start];
}

- (void)start {
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(start) object:nil];
    
    if (self.queue.count == 0) return;
    if (self.currentRequest != nil) return;
    
    RequestNormal *request = self.queue[0];
    [self.queue removeObjectAtIndex:0];
    
    self.currentRequest = request;
    
    __weak typeof(self) weakSelf = self;
    
    __block OnFailure onFailure = request.blockMap[@"onFailure"];
    __block OnSuccess onSuccess = request.blockMap[@"onSuccess"];
    [request.onFailure(^(NSError * _Nonnull error) {
        weakSelf.currentRequest = nil;
        if (onFailure != nil) onFailure(error);
        request.blockMap[@"onSuccess"] = onSuccess;
        request.blockMap[@"onFailure"] = onFailure;
        [weakSelf.queue addObject:request];
        [weakSelf performSelector:@selector(start) withObject:nil afterDelay: 15];

//        [weakSelf appendFailureNetRequest:request onSuccess:onSuccess];
        onSuccess = nil;
        onFailure = nil;
    }) onSuccess:^(id  _Nonnull response) {
        weakSelf.currentRequest = nil;
        if (onSuccess != nil) onSuccess(response);
        onSuccess = nil;
        onFailure = nil;
        if (weakSelf.queue.count == 0) {
            weakSelf.releaseBlock();
        } else {
            [weakSelf start];
        }
    }];
    
}

@end
